<template>
  <el-dialog
    :visible="visible"
    :before-close="handleClose"
    :close="handleClose"
    :show-close="!showMobilePage"
    :class="{'global-mobile-dialog':showMobilePage}"
    class="normal-common-dialog-size health-dialog"
  >
    <Title title="健康值设置" style="margin-bottom:24px" />
    <el-form
      ref="healthForm"
      :model="formData"
      :rules="rules"
      :inline="true"
      :class="{'mobile-health-view':showMobilePage}"
      class="form"
      size="small">
      <div v-for="(item, index) in formData.healthValue" :key="item.id" class="health-form">
        <el-form-item :prop="`healthValue.${index}.time`" :rules="rules.time">
          <el-select v-model="item.time" size="small" style="width: 130px;">
            <el-option v-for="it in timeOptions" :key="it.value" :label="it.label" :value="it.value" :disabled="isDisabled(it.value)"/>
          </el-select>
        </el-form-item>
        <el-form-item :prop="`healthValue.${index}.forward`" :rules="rules.forward" label="转发">
          <el-input-number v-model="item.forward" :controls="false" :precision="0" :min="0" :max="999999999" size="small" />
        </el-form-item>
        <el-form-item :prop="`healthValue.${index}.comment`" :rules="rules.comment" label="评论">
          <el-input-number v-model="item.comment" :controls="false" :precision="0" :min="0" :max="999999999" size="small" />
        </el-form-item>
        <el-form-item :prop="`healthValue.${index}.like`" :rules="rules.like" label="点赞">
          <el-input-number v-model="item.like" :controls="false" :precision="0" :min="0" :max="999999999" size="small" />
        </el-form-item>
        <el-button type="text" @click.native="handleDelete(item.id)">删除</el-button>
      </div>
    </el-form>
    <el-button :disabled="formData.healthValue.length >= 8" type="text" style="padding-top: 0;" @click.native="handleAdd">添加</el-button>
    <div style="margin-bottom: 16px;">注意：无效链接将无法正常采集。</div>
    <div class="center">
      <el-button
        :disabled="loading"
        :loading="loading"
        type="primary"
        size="small"
        @click="handleSubmit"
      >
        确定
      </el-button>
      <el-button
        type="info"
        size="small"
        class="cancel-btn-style"
        @click="handleClose"
      >取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import Title from '@/components/Title';
import { compare } from './utils';
import { mapState } from 'vuex';
export default {
  components: {
    Title
  },
  props: {
    list: {
      type: Array,
      default: () => []
    },
    isCache: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        healthValue: [{ id: 0, time: 0.5, forward: undefined, like: undefined, comment: undefined }]
      },
      visible: false,
      loading: false,
      timeOptions: [
        { label: '发文0.5小时内', value: 0.5 },
        { label: '发文1小时内', value: 1 },
        { label: '发文2小时内', value: 2 },
        { label: '发文4小时内', value: 4 },
        { label: '发文8小时内', value: 8 },
        { label: '发文12小时内', value: 12 },
        { label: '发文18小时内', value: 18 },
        { label: '发文24小时内', value: 24 }
      ]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    rules() {
      const res = {
        'time': [{ required: true, message: '请选择时间段', trigger: 'blur' }],
        'forward': [{ required: true, message: '请填写转发数', trigger: 'blur' }],
        'comment': [{ required: true, message: '请填写评论数', trigger: 'blur' }],
        'like': [{ required: true, message: '请填写点赞数', trigger: 'blur' }]
      };
      return res;
    }
  },
  methods: {
    openDialog() {
      if (!this.list.length && this.isCache) {
        // 保留上次修改的结果
        const localHealthValue = sessionStorage.getItem('healthValue');
        if (localHealthValue) {
          this.formData.healthValue = JSON.parse(localHealthValue);
        }
      }
      if (this.list && !this.isCache) {
        // 回填最后设置的结果
        if (this.list.length > 0) {
          // 处理旧数据id重复问题
          this.formData.healthValue = this.list.map(it => {
            return {
              ...it,
              id: Math.random()
            };
          });
        } else {
          this.formData.healthValue = [{ id: Math.random(), time: 0.5, forward: undefined, like: undefined, comment: undefined }];
        }
      }
      this.visible = true;
    },
    cancelLoading() {
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    isDisabled(v) {
      return this.formData.healthValue.some(it => it.time === v);
    },
    handleClose() {
      this.visible = false;
      this.$refs['healthForm'].resetFields();
      this.cancelLoading();
    },
    handleAdd() {
      const temp = [...this.formData.healthValue];
      temp.push({ id: Math.random(), time: null, forward: undefined, like: undefined, comment: undefined });
      this.formData.healthValue = temp;
    },
    handleDelete(id) {
      this.formData.healthValue = this.formData.healthValue.filter(it => it.id !== id);
    },
    handleSubmit() {
      this.$refs['healthForm'].validate(valid => {
        if (valid) {
          this.loading = true;
          const submitData = this.formData.healthValue.sort(compare('time'));
          if (this.isCache) {
            sessionStorage.setItem('healthValue', JSON.stringify(submitData));
          }
          this.$emit('submit', submitData);
        } else {
          this.$message.warning('请检查信息是否填写完整');
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.health-dialog {
  .center{
    display: flex;
    justify-content: center;
  }
  .row-item {
    display: flex;
    align-items: center;
    flex-flow: row nowrap;
    .row-item-label {
      font-size: 14px;
      color: #999;
      white-space: nowrap;
    }
  }
  &::v-deep {
    .el-button--text {
      font-size: 14px;
    }
  }
  .health-form {
    display: flex;
    align-items: center;
    justify-content: space-between;
    &::v-deep {
      .el-button {
        position: relative;
        bottom: 9px;
      }
    }
  }
}
.mobile-health-view {
  overflow-x: auto !important;
  ::v-deep .el-form-item {
          flex-shrink: 0 !important;
        }
}
</style>
